package top.xiaoshuaila.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.xiaoshuaila.pojo.Employee;
import top.xiaoshuaila.pojo.MailConstants;
import top.xiaoshuaila.pojo.MailLog;
import top.xiaoshuaila.service.IEmployeeService;
import top.xiaoshuaila.service.IMailLogService;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MailTask {
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;



    //使用Scheduled注解设置10s执行一次
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        //找出所有trytime到达的,且未确认(status=0)的mailLog
        List<MailLog> list = mailLogService.list(
                new QueryWrapper<MailLog>()
                        .eq("status", 0)
                        .lt("tryTime", LocalDateTime.now()));
        for (MailLog m:list){
            //当尝试次数大于等于3,将该数据状态设为失败(status=2)
            if(m.getCount()>=3) {
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("status", 2)
                        .eq("msgId", m.getMsgId()));
                System.out.println(m.getMsgId()+":邮件发送失败!!!");
            }
            else {
                //否则,通过mailLog中的eid找到employ表里的对象和msgid一起再次发送一遍
                Employee employees=
                         employeeService.getEmployee(m.getEid()).get(0);
                rabbitTemplate.convertAndSend(
                        MailConstants.EXCHANGE_NAME,
                        MailConstants.ROUTING_NAME,employees,
                        new CorrelationData(m.getMsgId()));
                System.out.println(m.getMsgId()+":重发成功!!");
            }
            //更新每条数据的修改时间,下次尝试最早数据,重发次数
            mailLogService.update(new UpdateWrapper<MailLog>()
                    .set("count",m.getCount()+1)
                    .set("updateTime",LocalDateTime.now())
                    .set("tryTime",
                            LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .eq("msgId",m.getMsgId()));
        }
    }
}
